package com.xiashitech.apiservice.config;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigChangeEvent;
import com.alibaba.nacos.api.config.ConfigChangeItem;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import com.xiashitech.apiservice.grpc.ConfigService;
import com.xiashitech.apiservice.service.IAgentConfigService;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

import java.util.Collection;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class AppConfig implements InitializingBean, ApplicationListener<WebServerInitializedEvent> {

    private final NacosConfigManager nacosConfigManager;
    private final ConfigService configPushService;
    private int serverPort;

    @Value("${grpc.server.port: 0}")
    private int grpcPort;

    // 用于接收 nacos 中配置更新，主动推送给 agent
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("afterPropertiesSet called");
        AbstractConfigChangeListener listener =
                new AbstractConfigChangeListener() {
                    @Override
                    public void receiveConfigChange(ConfigChangeEvent event) {
                        log.info("receiveConfigChange called");
                        Collection<ConfigChangeItem> changeItems = event.getChangeItems();
                        // 只是变化的项：[ConfigChangeItem{key='agent.systemAppCode.usegrpc', oldValue='123123', newValue='12323', type=MODIFIED}]
                        log.info(changeItems.toString());
                        // 在此时，AgentConfigDTO 中的配置信息还没有刷新的，但还是直接调用 pushConfigToAgent，在该方法中有延迟推送
                        configPushService.pushConfigToAgent();
                    }
                };
        this.nacosConfigManager
                .getConfigService()
                // 注意这里的 dataId，不需要没有扩展名
                .addListener("apiservice", "DEFAULT_GROUP", listener);
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
        log.info("Get WebServer port {}", serverPort);
    }

    public int getServerPort() {
        return serverPort;
    }

    public int getGrpcPort() {
        return grpcPort;
    }
    public void setGrpcPort(int port) {
        this.grpcPort = port;
    }
}
